package com.example.backblog.service.user.impl;

import com.example.backblog.entity.user.*;
import com.example.backblog.repository.user.*;
import com.example.backblog.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    UserRoleRepository userRoleRepository;
    @Autowired
    RolePermissionRepository rolePermissionRepository;
    @Autowired
    PermissionRepository permissionRepository;
    @Override
    public User getByUserName(String userName) {
        return userRepository.findFirstByNameEquals(userName);
    }

    @Override
    public List<Role> getUserRoles(String userName) {
        User user = this.getByUserName(userName);
        if (user != null) {
            Long userId = user.getId();
            List<UserRole> userRoles = userRoleRepository.findAllByUserIdEquals(userId);
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            List<Role> roles = roleRepository.findAllByIdIn(roleIds);
            return roles;
        }
        // 返回空集合
        return new ArrayList<>();
    }

    @Override
    public List<String> obtainPermission(List<Role> roles) {
        List<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
        List<RolePermission> rolePermissions = rolePermissionRepository.findAllByRoleIdIn(roleIds);
        List<Long> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> permissions = permissionRepository.findAllByIdIn(permissionIds);
        List<String> permissionNames = permissions.stream().map(Permission::getPermissionName).collect(Collectors.toList());
        return permissionNames;
    }

}
